package org.wanghong.gift.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wanghong.gift.dto.RegisterPhoneValidateDto;
import org.wanghong.gift.exception.asserts.Assert;
import org.wanghong.gift.exception.statuCode.StatusCode;
import org.wanghong.gift.service.ISmsValidateCodeService;
import org.wanghong.gift.util.AjaxResult;
import org.wanghong.gift.util.StrUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SmsValidateCodeServiceImpl implements ISmsValidateCodeService {
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public AjaxResult sendRegisterCode(String phone) {
        //1空检验
        Assert.assertNotEmpty(phone, StatusCode.CODE_400);

        //2 判断原来的验证码是否存在
        String key ="register_sms_code_" + phone;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue().get(key);
        String code = "";
        if(StringUtils.isEmpty(smsCodeOfRedis)) {
            // 如果不存在就产生新的,并放入redis中
            code = StrUtils.getRandomString(6);
        }else{
            //如果存在，判断是否过期，过期就产生新的，否则就用原来的
            code = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*1)
            {
                return AjaxResult.me().setSuccess(false).setMessage("非法请求，请重试");
            }
        }
        //记录验证码放到redis，过期时间为5分钟
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        //调用短信接口进行发送
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", code, 5);
        //SmsUtil.sendSms(mobile,content);
        System.out.println("已经成功发送了一条短信,内容为"+content);
        //发送的记录，待做
        return AjaxResult.me();
    }

    @Override
    public AjaxResult validateRegisterCode(RegisterPhoneValidateDto dto) {
        String phone = dto.getPhone();
        String validateCode = dto.getValidateCode();

        //从redis中获取验证码进行null判断
        String key ="register_sms_code_" + phone;
        String codeStr = (String) redisTemplate.opsForValue().get(key);
        Assert.assertNotEmpty(codeStr, StatusCode.CODE_400);

        //验证码比对
        String code = codeStr.split(":")[0];
        Assert.assertEqualsIgnoreCase(validateCode,code,StatusCode.CODE_400_CODE_NOT_EQUALS);
        return AjaxResult.me();
    }
}
